<?php
/**
 * 首页
 */

use app\config\Db;
use Core\Result\Result;
use Core\Utils\Utils;
use GuzzleHttp\Client;

/**
 * 首页信息 TODO
 * 轮播、最新公告、版本信息
 * @param $userTokenInfo
 * @return void
 */
function index($userTokenInfo)
{
}
/**
 * 轮播 TODO
 * @param $data
 * @return void
 */
function carousel($data)
{
    $identification = $data['identification'];
    $db = new Db();
    $data = $db->query("select `id`,`type`,`action`,`image_url` from `header_image` where identification = '$identification' and `approve_state` = 1 order by `sort` desc");
    foreach ($data as $k => $v) {
        $data[$k]["image_url"] = $v["image_url"]."?_rand=".mt_rand(100,999);
    }
    Result::success($data);
}
/**
 * 首页活动 TODO
 * @param
 * @return void
 */
function homeActiveList()
{
    $db = new Db();
    $data = $db->query("select id,img,`name`,`identificationName`,`remarks`,`stype`,`gid` from ysmz_active where state=1 and type = 1");
    foreach ($data as $k => $v) {
        $data[$k]["img"] = $v["img"]."?_rand=".mt_rand(100,999);
    }
    Result::success($data);
}
/**
 * 专区信息 TODO
 * @param
 * @return void
 */
function homeSectionList()
{
    $db = new Db();
    $data = $db->query("select `id`,`name`,`icon` from `ysmz_section` where state=1");
    foreach ($data as $k => $v) {
        $data[$k]["icon"] = $v["icon"]."?_rand=".mt_rand(100,999);
    }
    Result::success($data);
}
/**
 * 首页信息 TODO
 * 获取天气
 * @param $userTokenInfo
 * @return void
 */
function weatherInformation($data)
{
    $lat = $data['lat'];
    $lng = $data['lng'];
    $key = '62e537bf004e675ff1250c4ad3a8ad53';//高德
    //$key = 'OMQBZ-FA7CT-JAUXK-LPEAT-KMTFJ-ELBEQ';//腾讯
    $data = [];
    // 2. 获取地理位置（逆地理编码）
    $geoUrl = "https://restapi.amap.com/v3/geocode/regeo?location={$lat},{$lng}&key={$key}";//高德
    //$geoUrl = "https://apis.map.qq.com/ws/geocoder/v1/?location={$lng},{$lat}&key={$key}";//腾讯
    $geoJson = @file_get_contents($geoUrl);
    $geoData = json_decode($geoJson, true);
    if (!empty($geoData['status']) && $geoData['status'] == '1') {
        $address = $geoData['regeocode']['addressComponent'];
        $data['city'] = $address['district'] ?? $address['city'] ?? $address['province'] ?? '未知';
        $adcode = $address['adcode'] ?? '';
        if ($adcode) {
            $weather = "SELECT `name`,`realFeel`,`temp`,`condition`,`update_time` FROM `ysmz_weather` WHERE `adcode` = $adcode ORDER BY update_time desc limit 1";
            $db = new Db("host");
            $weatherInfo = $db->find($weather);
            $time = time();
            if(empty($weatherInfo) || $time - $weatherInfo["update_time"] >7200){
                $host = "https://aliv8.data.moji.com";
                $path = "/whapi/json/aliweather/condition";
                $appcode = "0a2286f6d2254e74a4133bc8e3cef016";
                $headers = [
                    "Authorization" => "APPCODE " . $appcode,
                    "Content-Type" => "application/x-www-form-urlencoded; charset=UTF-8"
                ];
                $bodys = "lat=$lng&lon=$lat&token=ff826c205f8f4a59701e64e9e64e01c4";
                $url = $host . $path;
                $client = new Client(['verify' => false]);
                $response = $client->post($url, [
                    'headers' => $headers,
                    'body' => $bodys
                ]);
                $statusCode = $response->getStatusCode();
                if($statusCode == 200){
                    $content = $response->getBody()->getContents();
                    $json_decode = json_decode($content, true);
                    if($json_decode["code"] ==0){
                        $counname = $json_decode["data"]['city']["counname"];
                        $name = $json_decode["data"]['city']["name"];
                        $pname = $json_decode["data"]['city']["pname"];
                        $realFeel = $json_decode["data"]['condition']["realFeel"];
                        $temp = $json_decode["data"]['condition']["temp"];
                        $condition = $json_decode["data"]['condition']["condition"];
                        if(empty($weatherInfo)){
                            $weatherSql = "INSERT INTO `ysmz_weather` (`adcode`, `counname`, `name`, `pname`, `realFeel`, `temp`, `condition`, `update_time`) VALUES ($adcode, '$counname', '$name', '$pname', '$realFeel', '$temp', '$condition', $time)";
                        }else{
                            $weatherSql = "UPDATE `ysmz_weather` SET `realFeel` = '$realFeel', `temp` = '$temp', `condition` = '$condition', `update_time` = $time WHERE `adcode` = $adcode";
                        }
                        $db->save($weatherSql);
                        $resData['city'] = $name;
                        $resData['daytemp'] = $realFeel;
                        $resData['nighttemp'] = $temp;
                        $resData['weather'] = $condition;
                    }
                }
            }else{
                $resData['city'] = $weatherInfo["name"];
                $resData['daytemp'] = $weatherInfo["realFeel"];
                $resData['nighttemp'] = $weatherInfo["temp"];
                $resData['weather'] = $weatherInfo["condition"];
            }
            Result::success($resData);
        } else {
            Result::error("adcode 获取失败");
        }
    } else {
        Result::error("位置信息获取失败");
    }
}
/**
 * 弹窗公告 TODO
 * @param
 * @return void
 */
function newNotice()
{
    $db = new Db();
    $time = time();
    $data = $db->find("select id,title,content,create_date,pop_date from `platform_notice_message` where `type` = 2 order by create_date desc limit 1");
    $cresteTime = strtotime($data['pop_date']);
    if ($time > $cresteTime) $data = [];
    Result::success($data);
}
/**
 * 弹窗广告 TODO
 * @param
 * @return void
 */
function newAdvertising()
{
    $db = new Db();
    $dateTime = Utils::dateTime(time());
    $data = $db->query("select id,title,content,create_date,pop_date,type,gid from `platform_advertising_message` where `pop_date` > '$dateTime' order by pop_date desc");
    Result::success($data);
}
/**
 * 公告列表 TODO
 * @param
 * @return void
 */
function noticeList($data)
{
    $page = $data["page"];
    $limit = $data["limit"];
    $db = new Db();
    $data = $db->query("select id,title,content,create_date from platform_notice_message order by create_date desc limit $page,$limit");
    Result::success($data);
}

/**
 * 版本列表 TODO
 * @return json
 */
function versionList($data)
{
    $platform_name = $data["platform_name"];
    $page = $data["page"];
    $limit = $data["limit"];
    $platform_name = $platform_name ?? 'android';
    $db = new Db();
    $data = $db->query("select id,version_name,update_log,create_date from version_control where platform_name='$platform_name' order by id desc limit $page,$limit");
    Result::success($data);
}
/**
 * 协议 TODO
 * 协议ID【1用户协议2隐私协议】
 * @return void
 */
function agreement($data)
{
    $content_id =$data['content_id'];
    $db = new Db();
    $content = $db->find("select content from ysmz_cms_content where content_id=$content_id limit 1");
    if (!$content) Result::error("内容不存在");
    header("Content-Type:text/html;charset=utf-8");
    Result::success($content['content']);
}

